package it.antonio.ilpizze.db.core;

import it.antonio.ilpizze.db.Security;
import it.antonio.ilpizze.db.core.fs.SecurityFile;
import it.antonio.ilpizze.db.security.Role;
import it.antonio.ilpizze.db.security.User;
import it.antonio.ilpizze.func.Pair;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SecurityDbManager implements Security {
	
	private SecurityFile securityFile;
	private StatusManager statusManager;
	private LockManager lockManager;
	
	public SecurityDbManager(SecurityFile securityFile, StatusManager statusManager, LockManager lockManager) {
		this.securityFile = securityFile;
		this.statusManager = statusManager;
		this.lockManager = lockManager;
	}

	@Override
	public User user(String name) {
		statusManager.checkStatus(Status.OPEN);
		lockManager.checkMultiThreadingRead();
		
		User user = securityFile.get(name);
		return user;
	}

	
	@Override
	public void changePassword(String name, String newPw) {
		statusManager.checkStatus(Status.OPEN);
		lockManager.checkMultiThreadingWrite();
		
		User user = securityFile.get(name);
		if(user !=  null){
			User newUser = new User(user.name(), newPw, user.role());
			securityFile.put(user.name(), newUser);
		}
	}

	@Override
	public void addUser(String name, String password, Role role) {
		statusManager.checkStatus(Status.OPEN);
		lockManager.checkMultiThreadingWrite();
		
		securityFile.put(name, new User(name, password, role));
	}

	@Override
	public void removeUser(String name) {
		statusManager.checkStatus(Status.OPEN);
		lockManager.checkMultiThreadingWrite();
		
		securityFile.remove(name);
	}
	
	@Override
	public List<User> users() {
		statusManager.checkStatus(Status.OPEN);
		lockManager.checkMultiThreadingRead();
		
		Iterator<Pair<String, User>> it = securityFile.iterator();
		List<User> rUsers = new ArrayList<User>();
		while(it.hasNext()){
			rUsers.add(it.next().second());
		}
		return rUsers;
	}

	
	
	
	public void runMaintenance(DbFileSystem dbfs) {
		// TODO Auto-generated method stub
		
	}

	
	
	
	
	
	
	
	
	
}
